#include"kostukovich_850505_openssl.h"
#if WIN32
#include<stdlib.h>
#include<malloc.h>
#include<stdio.h>
#include<windows.h>
#else
#include<pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#endif
int enc=0;
char *key;
int file(char *in, char *out)
	   {
		 int i;
         FILE *OpenFile, *ResultFile,*BUFF;
		 char block[8],block_1;
                 long kol=0;
		 for(i=0;i<=7;i++)
		 {
			 block[i]=0;
		 }
         OpenFile=fopen(in,"rb");
         ResultFile=fopen(out,"wb");
		 if(!OpenFile || !ResultFile)
		 {
           printf("ERROR!!! FILE was not opened!!!");
		   return -1;
		 }
		 while(fread(block,8,sizeof(char),OpenFile))
		 {
                     
                     
			 crypto(key,block,ResultFile,enc);
			 for(i=0;i<=7;i++)
		     {
			 block[i]=0;
		     }
                     kol = ftell(OpenFile);
		 }
                 fseek(OpenFile, kol, SEEK_SET);
                 if(feof(OpenFile)) printf("END FILE");
                 while(!feof(OpenFile))
		 {
                        if(fread(&block_1,1,sizeof(char),OpenFile)!=1) if(feof(OpenFile)) break;
			fwrite(&block_1,1,sizeof(char),ResultFile);
                        
		 }
                 
                 
	   }
#if WIN32
       int win_main(int argc,char **argv)
	   {
		   char prov[1]={'e'};
		   key=argv[4];
		   if(argv[3][0]==prov[0]) enc=1;
		   else {enc=0;} 
		   file(argv[1],argv[2]);
		 return 0;
	   }
#else
	   int lin_main(int argc,char **argv)
	   {   
	    char *in, *out;
	    int rez=0;

            while ( (rez = getopt(argc,argv,"edi:o:k:")) != -1)
            {
		switch (rez)
                {
		case 'e': enc=1; break;
		case 'o': out=optarg; break;
		case 'i': in=optarg; break;
		case 'd': enc=0; break;
		case 'k': key=optarg; break;
		case '?': printf("Error found !\n");break;
                }
             }
             file(in,out);
             return 0;
	   }
#endif
int main(int argc,char **argv)
{
    #if WIN32
	win_main(argc,argv);
    #else
    lin_main(argc,argv);
	#endif
    return 0;
}
